package com.fxu.framework.biz.util;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * UUID获取类
 * @author fangxu
 * @version 1.0.0
 */
@Component
public final class UUIDUtil {
	private final static SimpleDateFormat smallFormatter = new SimpleDateFormat("yyyyMMddHHmm");
	private final static String fill = "0000000000000000000000000000";
	
	/** uuid的长度，没有配置是32位 */
	@Value("${uuid-length:32}")
    private int uuidLength;
	
	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * <p>自动生成uuidLength位的UUid，对应数据库的主键id添加数据用。</p>
	 * @return 返回UID
	 */
	private String getUID(String bean) {
		String clz = getSmall(StrUtil.upperFirst(bean));
		// 补充完32位
		String uuid = clz + smallFormatter.format(new Date());
		long id = redisTemplate.opsForValue().increment("UUID_KEY_" + bean);
		if (uuid.length() <= 0) {
			uuid = "";
		}
		String uid = fill + id;
		final int len1 = uid.length();
		final int len2 = uuid.length();
		return uuid + uid.substring(len1 - (uuidLength - len2), len1);
	}
	
	public final String getUUID(Class<?> clazz) {
		return getUID(clazz.getSimpleName());
	}
	
	public static void main(String[] args) {
		System.out.println("仅提供给maven打包jar使用，不能启动服务!");
	}
	
	/** 类缓存 */
	private final static Map<String, String> CLASS_MAP = new ConcurrentHashMap<>();

	private static String getSmall(String tableBean) {
		String temp = CLASS_MAP.get(tableBean);
		if (null != temp) {
			return temp;
		}
		StringBuilder result = new StringBuilder();
		for (int i = 0, len = tableBean.length(); i < len; i++) {
			if (Character.isUpperCase(tableBean.charAt(i))) {
				result.append(tableBean.charAt(i));
			}
			if (i == len - 1 && result.length() < 3) {
				result.append(tableBean.charAt(i));
			}
		}
		CLASS_MAP.put(tableBean, result.toString());
		return result.toString();
	}
}
